/**
 * 图片上传到MinIO服务的通用方法
 */

/**
 * 上传图片到MinIO
 * @param {string} filePath 本地文件路径
 * @param {string} uploadType 上传类型：'avatar' | 'image'
 * @returns {Promise} 上传结果
 */
export function uploadImageToMinio(filePath, uploadType = 'image') {
  const token = wx.getStorageSync('token');
  
  if (!token) {
    return Promise.resolve({
      success: false,
      message: '请先登录'
    });
  }

  const uploadUrl = uploadType === 'avatar' 
    ? 'http://localhost:8080/api/wx/upload/avatar'
    : 'http://localhost:8080/api/wx/upload/image';
  
  return new Promise((resolve) => {
    wx.uploadFile({
      url: uploadUrl,
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': token
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          if (res.statusCode === 200 && data.url) {
            console.log(`图片已成功上传到MinIO (${uploadType}):`, data.url);
            resolve({
              success: true,
              url: data.url,
              message: data.message || '上传成功'
            });
          } else {
            resolve({
              success: false,
              message: data.message || '上传失败'
            });
          }
        } catch (e) {
          console.error('响应解析失败:', e, res.data);
          resolve({
            success: false,
            message: '响应解析失败'
          });
        }
      },
      fail: (err) => {
        console.error('图片上传失败:', err);
        resolve({
          success: false,
          message: '网络请求失败'
        });
      }
    });
  });
}

/**
 * 选择并上传图片的完整流程
 * @param {object} options 配置选项
 * @param {string} options.uploadType 上传类型
 * @param {number} options.maxSize 最大文件大小（字节）
 * @param {Array} options.sizeType 图片尺寸类型
 * @param {Array} options.sourceType 图片来源
 * @returns {Promise} 包含选择和上传的完整结果
 */
export function chooseAndUploadImage(options = {}) {
  const {
    uploadType = 'image',
    maxSize = 10 * 1024 * 1024, // 10MB
    sizeType = ['compressed'],
    sourceType = ['album', 'camera']
  } = options;

  return new Promise((resolve, reject) => {
    // 1. 选择图片
    wx.chooseImage({
      count: 1,
      sizeType,
      sourceType,
      success: async (res) => {
        try {
          const { path, size } = res.tempFiles[0];
          
          // 2. 检查文件大小
          if (size > maxSize) {
            resolve({
              success: false,
              message: `图片大小不能超过${Math.floor(maxSize / 1024 / 1024)}MB`
            });
            return;
          }

          // 3. 显示上传进度
          wx.showLoading({
            title: '正在上传图片...',
          });

          // 4. 上传到MinIO
          const uploadResult = await uploadImageToMinio(path, uploadType);
          
          wx.hideLoading();
          
          resolve(uploadResult);

        } catch (error) {
          wx.hideLoading();
          resolve({
            success: false,
            message: error.message || '上传失败'
          });
        }
      },
      fail: (err) => {
        if (err.errMsg === 'chooseImage:fail cancel') {
          resolve({
            success: false,
            message: '用户取消选择',
            cancelled: true
          });
        } else {
          resolve({
            success: false,
            message: '选择图片失败'
          });
        }
      }
    });
  });
}

/**
 * 批量上传图片
 * @param {Array} filePaths 文件路径数组
 * @param {string} uploadType 上传类型
 * @returns {Promise} 批量上传结果
 */
export function batchUploadImages(filePaths, uploadType = 'image') {
  const uploadPromises = filePaths.map(filePath => 
    uploadImageToMinio(filePath, uploadType)
  );
  
  return Promise.all(uploadPromises);
}
